package com.sj.security;

import cn.hutool.core.util.StrUtil;
import com.sj.common.exception.CustomException;
import com.sj.common.lang.Const;
import com.sj.utils.MineUtils;
import com.sj.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-08-02
 * Time: 下午 12:38
 * Description: 验证码校验过滤器
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Autowired
    private MineUtils mineUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();

        // 如果是 登录请求 就拦截 进行验证码校验
        if (Const.LOGIN_URL.equals(url) && request.getMethod().equals(Const.POST_METHOD)) {
            //校验验证码
            try {
                mineUtils.validate(request);
            } catch (CustomException e) {

                // 如果验证码不正确 交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        // 认证成功 或者 不是被拦截的请求 直接放行
        filterChain.doFilter(request, response);
    }

}